package com.ruoyi.framework.manager;

import java.util.TimerTask;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import com.ruoyi.common.utils.Threads;
import com.ruoyi.common.utils.spring.SpringUtils;

/**
 * 异步任务管理器
 * 
 * @author ruoyi
 */
public class AsyncManager
{
    /**
     * 操作延迟10毫秒
     */
    private final int OPERATE_DELAY_TIME = 10;

    /**
     * 异步操作任务调度线程池
     */
    private volatile ScheduledExecutorService executor;

    /**
     * 单例模式
     */
    private AsyncManager(){}

    private static volatile AsyncManager me;
    
    public static AsyncManager me()
    {
        if (me == null)
        {
            synchronized (AsyncManager.class)
            {
                if (me == null)
                {
                    me = new AsyncManager();
                }
            }
        }
        return me;
    }



    /**
     * 获取执行器
     */
    private ScheduledExecutorService getExecutor()
    {
        if (executor == null)
        {
            synchronized (this)
            {
                if (executor == null)
                {
                    try
                    {
                        // 检查 Spring 容器是否已经初始化
                        if (isSpringContextInitialized() && SpringUtils.containsBean("scheduledExecutorService"))
                        {
                            executor = SpringUtils.getBean("scheduledExecutorService");
                            System.out.println("AsyncManager: Successfully obtained scheduledExecutorService from Spring context");
                        }
                        else
                        {
                            createDefaultExecutor();
                        }
                    }
                    catch (Exception e)
                    {
                        // 如果获取Spring bean失败，创建一个默认的线程池
                        System.out.println("AsyncManager: Failed to get scheduledExecutorService from Spring context, creating default executor: " + e.getMessage());
                        createDefaultExecutor();
                    }
                }
            }
        }
        return executor;
    }
    
    
    /**
     * 检查Spring容器是否已经初始化
     */
    private boolean isSpringContextInitialized()
    {
        try
        {
            // 尝试获取ApplicationContext，如果抛出异常说明Spring容器还未初始化
            return SpringUtils.getApplicationContext() != null;
        }
        catch (Exception e)
        {
            return false;
        }
    }
    
    /**
     * 创建默认的执行器
     */
    private void createDefaultExecutor()
    {
        System.out.println("AsyncManager: Creating default ScheduledExecutorService");
        executor = java.util.concurrent.Executors.newScheduledThreadPool(10,
            r -> {
                Thread t = new Thread(r, "AsyncManager-" + System.currentTimeMillis());
                t.setDaemon(true);
                return t;
            });
    }

    /**
     * 执行任务
     * 
     * @param task 任务
     */
    public void execute(TimerTask task)
    {
        if (task == null)
        {
            return;
        }
        
        try
        {
            ScheduledExecutorService executorService = getExecutor();
            if (executorService != null && !executorService.isShutdown())
            {
                executorService.schedule(task, OPERATE_DELAY_TIME, TimeUnit.MILLISECONDS);
            }
            else
            {
                // 如果线程池不可用，直接同步执行
                task.run();
            }
        }
        catch (Exception e)
        {
            // 如果异步执行失败，直接同步执行任务
            System.out.println("AsyncManager: Failed to execute task asynchronously, executing synchronously: " + e.getMessage());
            try
            {
                task.run();
            }
            catch (Exception taskException)
            {
                System.err.println("AsyncManager: Failed to execute task: " + taskException.getMessage());
                taskException.printStackTrace();
            }
        }
    }

    /**
     * 停止任务线程池
     */
    public void shutdown()
    {
        if (executor != null)
        {
            Threads.shutdownAndAwaitTermination(executor);
        }
    }
}
